<template>
  <div class="app-container">
    <!-- 使用Element Plus的卡片组件作为容器 -->
    <el-card class="box-card" v-loading="loading" element-loading-text="正在分析数据中，请稍候...">
      <!-- 卡片头部区域 -->
      <template #header>
        <div class="card-header">
          <div class="left-section">
            <el-tooltip
              content="选择要分析的时间范围"
              placement="top"
              effect="light"
            >
              <span class="title">时间:</span>
            </el-tooltip>
            <el-select 
              v-model="days" 
              placeholder="选择时间范围" 
              @change="fetchData" 
              class="time-select"
            >
              <el-option label="最近7天" :value="7" />
              <el-option label="最近15天" :value="15" />
              <el-option label="最近30天" :value="30" />
            </el-select>
          </div>
          <div class="right-section">
            <el-tooltip
              :content="selectedWords.length ? `已选择 ${selectedWords.length} 个词` : '请先选择要添加的停止词'"
              placement="top"
              effect="light"
            >
              <el-button
                type="primary"
                :disabled="!selectedWords.length"
                @click="handleAddStopWords"
                class="add-stop-words-btn"
                :icon="Plus"
              >
                添加为停止词
              </el-button>
            </el-tooltip>
          </div>
        </div>
      </template>
      <div class="content-container">
        <div class="word-cloud-section">
          <div class="section-title">词云可视化</div>
          <div class="word-cloud-container" ref="wordCloudRef"></div>
        </div>
        <div class="data-section">
          <div class="section-title">
            关键词统计
            <span class="data-count" v-if="wordData.length">
              (共 {{ wordData.length }} 个)
            </span>
          </div>
          <el-table 
            :data="wordData" 
            height="calc(100% - 40px)" 
            style="width: 100%"
            @selection-change="handleSelectionChange"
            :header-cell-style="{
              background: '#f5f7fa',
              color: '#606266'
            }"
            highlight-current-row
            border
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="word" label="关键词" min-width="60" align="center"/>
            <el-table-column 
              prop="frequency" 
              label="出现次数" 
              sortable 
              width="250"
              align="center"
            >
              <template #default="{ row }">
                <el-tag 
                  :type="getTagType(row.frequency)" 
                  effect="light"
                  size="small"
                >
                  {{ row.frequency }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
// 导入所需的Vue组件和功能
import { ref, onMounted, onUnmounted, computed } from "vue";
// 导入ECharts核心库
import * as echarts from "echarts";
// 导入ECharts词云图扩展
import "echarts-wordcloud";
// 导入API请求函数
import { getWordCloudData, addStopWords } from "@/api/chat";
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

// 定义响应式变量：时间范围，默认为7天
const days = ref(7);
// 定义词云图表容器的引用
const wordCloudRef = ref(null);
// 定义图表实例变量
let chartInstance = null;
// 定义加载状态
const loading = ref(false);
// 在script setup中添加一个新的响应式变量来存储词云数据
const wordData = ref([]);
const selectedWords = ref([]); // 新增：选中的词列表

/**
 * 初始化ECharts图表
 * 如果已存在实例，先销毁后重新创建
 */
const initChart = () => {
  if (chartInstance) {
    chartInstance.dispose();
  }
  chartInstance = echarts.init(wordCloudRef.value);
};

/**
 * 获取词云数据并更新图表
 * 从API获取数据后配置并渲染词云图
 */
const fetchData = async () => {
  loading.value = true;
  try {
    const { data } = await getWordCloudData(days.value);
    
    if (!data) {
      ElMessage.warning('未获取到数据');
      return;
    }

    wordData.value = data.map(item => ({
      word: item.word,
      frequency: item.frequency
    })).sort((a, b) => b.frequency - a.frequency);

    const option = {
      tooltip: {
        show: true,
        formatter: function (params) {
          return `${params.data.word}: ${params.data.frequency}次`;
        },
        backgroundColor: 'rgba(255,255,255,0.9)',
        textStyle: {
          color: '#666'
        },
        borderColor: '#eee',
        borderWidth: 1
      },
      series: [
        {
          type: "wordCloud",
          shape: "circle",
          left: 0,
          top: "center",
          width: "100%",
          height: "100%",
          right: null,
          bottom: null,
          sizeRange: [14, 80],
          rotationRange: [0, 0],
          rotationStep: 15,
          gridSize: 8,
          drawOutOfBound: false,
          textStyle: {
            fontFamily: "sans-serif",
            fontWeight: "bold",
            color: function () {
              // 生成蓝色调的随机颜色
              return (
                "rgb(" +
                [
                  Math.round(Math.random() * 200), // 降低红色比例
                  Math.round(Math.random() * 200), // 适中的绿色比例
                  Math.round(Math.random() * 200) // 提高蓝色比例
                ].join(",") +
                ")"
              );
            },
          },
          // 高亮样式配置
          emphasis: {
            textStyle: {
              shadowBlur: 10,
              shadowColor: "#333",
            },
          },
          // 转换数据格式
          data: data.map((item) => ({
            name: item.word,
            value: item.frequency,
            word: item.word,
            frequency: item.frequency,
          }))
        }
      ]
    };

    chartInstance.setOption(option);
  } catch (error) {
    console.error("获取词云数据失败:", error);
    ElMessage.error('获取数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

/**
 * 处理窗口大小改变事件
 * 调整图表大小以适应新的容器尺寸
 */
const handleResize = () => {
  chartInstance && chartInstance.resize();
};

/**
 * 组件挂载时的生命周期钩子
 * 初始化图表、获取数据并添加窗口resize事件监听
 */
onMounted(() => {
  initChart();
  fetchData();
  window.addEventListener("resize", handleResize);
});

/**
 * 组件卸载时的生命周期钩子
 * 清理图表实例和事件监听，防止内存泄漏
 */
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  window.removeEventListener("resize", handleResize);
});

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedWords.value = selection.map(item => item.word);
};

// 处理添加停止词
const handleAddStopWords = async () => {
  if (!selectedWords.value.length) {
    ElMessage.warning('请先选择要添加的停止词');
    return;
  }

  try {
    await addStopWords(selectedWords.value);
    ElMessage.success('停止词添加成功');
    // 重新加载数据
    fetchData();
  } catch (error) {
    console.error('添加停止词失败:', error);
    ElMessage.error('添加停止词失败，请稍后重试');
  }
};

// 根据频率返回不同的标签类型
const getTagType = (frequency) => {
  if (frequency >= 50) return 'danger';
  if (frequency >= 20) return 'warning';
  if (frequency >= 10) return 'success';
  return 'info';
};
</script>

<style scoped>
/* 容器样式 */
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

/* 时间选择框样式 */
.time-select {
  width: 130px;
}

/* 词云图表容器样式 */
.content-container {
  display: flex;
  gap: 24px;
  height: 65rem;
  margin-top: 20px;
}

.word-cloud-section, .data-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.05);
}

.word-cloud-section {
  flex: 2;
}

.data-section {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #ebeef5;
}

.data-count {
  font-size: 13px;
  color: #909399;
  font-weight: normal;
  margin-left: 8px;
}

.word-cloud-container {
  height: calc(100% - 45px);
  border-radius: 4px;
}

:deep(.el-table) {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-button) {
  transition: all 0.3s;
}

:deep(.el-button:not([disabled]):hover) {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

:deep(.el-tag) {
  transition: all 0.3s;
}

:deep(.el-tag:hover) {
  transform: scale(1.05);
}

:deep(.el-card__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 15px 20px;
}

.add-stop-words-btn {
  font-weight: 500;
}

:deep(.el-select-dropdown__item) {
  padding: 0 20px;
}

:deep(.el-table__row) {
  transition: all 0.3s;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa !important;
}
</style>
